<?php

namespace App\Services;

use App\Exceptions\ApiException;
use App\Exceptions\BaseException;
use App\Models\AuthenticLog;
use App\Models\Goods;
use App\Models\MemberOther;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use Illuminate\Support\Facades\Log;
use esign\emun\HttpEmun;
use esign\comm\EsignHttpHelper;
use esign\comm\EsignLogHelper;
class EsignV3Service
{
    //合同签署状态
    public static $connectTimeout = 30;//30 second
    public static $readTimeout = 80;//80 second
    const ESIGN_STATUS_DRAFT = 0;//草稿
    const ESIGN_STATUS_SIGNING = 1;//签署中
    const ESIGN_STATUS_FINISH = 2;//完成
    const ESIGN_STATUS_CANCEL = 3;//撤销
    const ESIGN_STATUS_OVERDUE = 5;//过期
    const ESIGN_STATUS_REFUSE = 7;//拒签

    //合同签署模板
    const ESIGN_SHOP_TWO = 1;//平台两方合同
    const ESIGN_SELF_TWO = 2;//自营两方合同
    const ESIGN_SHOP_THREE = 3;//三方合同


    public static function timevaleInit(){
        $arr = array("projectId"=>config('esign.APPID'),"projectSecret"=>config('esign.SECRET'),
            "itsmApiUrl"=>'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2');
        $data['projectConfig'] =$arr;

        $data = json_encode($data);
        $return_content = self::doPost(config('esign.API_HOST_V3').'/timevale/init',$data);
        $result = (array)json_decode($return_content,true);
        self::addLog('初始化sdk',$data,$return_content);
        var_dump($result);
    }





    //创建个人账户
    public static function addPersonAccountID($name,$idNumber){
        $arr = array(
            'idNoType'=>'MAINLAND',
            'name'=>$name,
            'idNo'=>$idNumber);
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.API_HOST_V3').'/timevale/account/addPerson',$data);
        $result = (array)json_decode($return_content,true);
        self::addLog('创建个人账户V3',$data,$return_content);
        return $result;
    }

    //签署流程查询
    public static function signStatus($fileId){
        $addaDocumnet = str_replace('{signFlowId}',$fileId,config('esign.API_HOST').'/v3/sign-flow/{signFlowId}/detail');
        $return_content = self::get_data($addaDocumnet);
        $result = (array)json_decode($return_content,true);
        self::addLog('签署流程查询',$addaDocumnet,$return_content);
        if(!empty($result['data'])){
            $result['data']['flowStatus']=$result['data']['signFlowStatus'];
            return $result['data'];
        }
    }

    //获取签署地址
    public static function executeUrl($flowId,$accountId){
        $addaDocumnet = str_replace('{flowId}',$flowId,config('esign.executeUrl'));
        $url = $addaDocumnet.'?accountId='.$accountId;
        $return_content = self::get_data($url,config('esign.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('获取签署地址',$addaDocumnet,$return_content);
        if(isset($result['data']) && !empty($result['data']['url'])){
            return $result['data']['url'];
        }
    }

    //修改个人签署账号
    public static function updateAccounts($accountId,$cert_no,$name){
        $arr = array(
            'accountId'=>$accountId,
            'name'=>$name
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.API_HOST_V3').'/timevale/account/updatePerson',$data);
        $result = (array)json_decode($return_content,true);
        self::addLog('修改个人签署账号',$data,$return_content);

        $arr = array(
            'idNo'=>$cert_no,
            'idNoType'=>'MAINLAND',
            'accountType'=>'PERSON'
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.API_HOST_V3').'/timevale/account/queryByIdNo',$data);
        $result = (array)json_decode($return_content,true);
        self::addLog('根据证件号查询签署账号信息',$data,$return_content);
        if(isset($result) && !empty($result['accountId'])){
            return $result['accountId'];
        }
    }

    // 1 创建企业账号
    public static function addFaAccountID($thirdPartyUserId,$name,$idNumber,$mobile){
        $arr = array(
            'thirdPartyUserId'=>$thirdPartyUserId,
            'name'=>$name,
            'orgCode'=>$idNumber,
            'regType'=>'MERGE',
            'mobile'=>$mobile
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.API_HOST_V3').'/timevale/account/addOrganize',$data);
        $result = (array)json_decode($return_content,true);
        self::addLog('创建企业法人账号',$data,$return_content);
        if($result['errCode']==0 && !empty($result['accountId'])){
            return $result['accountId'];
        }
    }

    // 2 创建平台账号
    public static function addTerraceAccountId($thirdPartyUserId,$creator,$name,$idNumber){
        $arr = array(
            'thirdPartyUserId'=>$thirdPartyUserId,
            'creator'=>$creator,
            'name'=>$name,
            'idType'=>"CRED_ORG_USCC",
            'idNumber'=>$idNumber
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.addOrganizeAccountID'),$data,config('esign.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('创建平台账号',$data,$return_content);
        if($result['errCode']==0 && !empty($result['accountId'])){
            return $result['accountId'];
        }
    }

    // 3 创建机构模板印章
    public static function addOrganizeSeals($orgId){
        $arr = array(
            'accountId'=>$orgId,
            'templateType'=>'STAR',
            'color'=>"RED"
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.API_HOST_V3').'/timevale/seal/createOfficialSeal',$data);
        $result = (array)json_decode($return_content,true);
        self::addLog('创建机构模板印章',$data,$return_content);
        if(isset($result['sealData']) && !empty($result['sealData'])){
            return $result['sealData'];
        }
    }


    //【线上】发起企业授权书签署任务
    public static function authCreate(){
        $data = [
            'organizeId'=>'46C6C1C679B64E519C19EBD635334914',
            'contact'=>'15501656160',
            'validDate'=>strtotime('+50 years').'000',
        ];
        $data = json_encode($data);
      return  self::doPost(config('esign.API_HOST_V3').'/timevale/auth/create',$data);

        self::addLog('发起企业授权书签署任务',$data,$return_content);

        return  $result = (array)json_decode($return_content,true);

        if(isset($result['sealData']) && !empty($result['sealData'])){
            return $result['sealData'];
        }
    }
    //【线上】获取授权签署任务链接
    public static function getAuthFlowUrl(){
        $data = [
            'authId'=>'3664107148293977908',
        ];
        $data = json_encode($data);
        return  self::doPost(config('esign.API_HOST_V3').'/timevale/auth/getAuthFlowUrl',$data);

        self::addLog('发起企业授权书签署任务',$data,$return_content);

        return  $result = (array)json_decode($return_content,true);

        if(isset($result['sealData']) && !empty($result['sealData'])){
            return $result['sealData'];
        }
    }





    //申请出证
    public static function createEvil()
    {
        $data = [
//            'streamFile'=>file_get_contents('租赁合同支付宝端20241110.pdf'),
            'createEviParam' => json_encode([
                'fileName' => '租赁合同',
                'srcPdfFile' => '/www/wwwroot/apishop.doulaizuji.com/public/pdf/20241119162331726427.pdf',
            ])
        ];
       return $return_content = self::doMultipart(config('esign.API_HOST_V3') . '/timevale/evi/createEvi', $data);

//        self::addLog('发起企业授权书签署任务', $data, $return_content);
//
//        return $result = (array)json_decode($return_content, true);
//
//        if (isset($result['sealData']) && !empty($result['sealData'])) {
//            return $result['sealData'];
//        }
    }

        //查询出证结果
    public static function queryEviResult(){
        $data = [
//            'streamFile'=>file_get_contents('租赁合同支付宝端20241110.pdf'),
            'createEviParam'=>json_encode([
                'fileName'=>'租赁合同',
                'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/20241119162331726427.pdf',
            ])
        ];
        return    $return_content = self::doPost(config('esign.API_HOST_V3').'/timevale/evi/queryEviResult',$data);
    }


    //【线上查询授权结果
    public static function authQuery(){
        $data = [
            'authId'=>'3643892854214366111',
        ];
        $data = json_encode($data);
        return  self::doPost(config('esign.API_HOST_V3').'/timevale/auth/query',$data);

        self::addLog('线上查询授权结果',$data,$return_content);

        return  $result = (array)json_decode($return_content,true);

        if(isset($result['sealData']) && !empty($result['sealData'])){
            return $result['sealData'];
        }
    }


    public static function platformSign(){
        $data = [
            'streamFile'=>file_get_contents('租赁合同支付宝端20241120.pdf'),
            'templateFillParam'=>json_encode([
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                ],
                'txtFields'=>['name'=>'123']
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/platform/sign',$data);

        self::addLog('填充本地PDF模板文件',$data,$return_content);

        return  $result = (array)json_decode($return_content,true);

        if(isset($result['sealData']) && !empty($result['sealData'])){
            return $result['sealData'];
        }
    }

    //三方合同签署
    //创建合同模板填充本地PDF模板文件
    public static function createFlowOneStepShopThree($order,$shop_user,$member){
        if ($order['pay_type']==1){
            $pay_type='智能合同代扣';
        }elseif ($order['pay_type']==2){
            $pay_type='预授权';
        }elseif ($order['pay_type']==3){
            $pay_type='花呗';
        }elseif ($order['pay_type']==4){
            $pay_type='全额买断';
        }else{
            $pay_type='未知';
        }
        //买断价
        $fisrt_month_rent = OrderLease::where('order_id',$order['id'])->where("which_period",1)->value("rent");
        $month_rent = OrderLease::where('order_id',$order['id'])->where("which_period","2")->value("rent");
        if(!strstr($order['address'],'省')||!strstr($order['address'],'市')){
            $order['address']=$order['prov'].$order['city'].$order['area'].$order['address'];
        }


        $orderLease = OrderLease::getPayTime($order);
        foreach ($orderLease as $k=>$v){
            $order_arr['simpleFormFields']['pay_time'.$v['which_period']] = date('Y年m月d日',$v['begin_time']);
            $order_arr['simpleFormFields']['month_rent'.$v['which_period']] = $v['rent'].'元';
        }
        if(count($orderLease) < 12){
            $lastNum = count($orderLease)+1;
            for($i=$lastNum;$i<=12;$i++){
                $order_arr['simpleFormFields']['pay_time'.$i] = '---';
                $order_arr['simpleFormFields']['month_rent'.$i] = '---';
            }
        }


        $txtFields=array(
            'order_sn' => $order['trade_no'],
            'first_name' => $shop_user['mechanism'],
            'first_address' => str_replace('-','',$shop_user['company_area']).$shop_user['company'],
//                'first_address' => $shop_user['company'],
            'first_code' => $shop_user['companyid'],
            'first_mobile' => $shop_user['contact_tel'],
            'user_name' => $order['cert_name'],
            'user_address' => $order['address'],
            'user_idcard' => $order['cert_no'],
            'user_mobile' => $order['user_mobile'],
            'third_name' => '',
            'third_address' => '上海市松江区小昆山镇港业路216号',
            'third_code' => '91310117MAE30K4D1P',
            'third_mobile' => '15501656160',
            'order_no' => $order['trade_no'],
            'user_data' => $order['cert_name'].'('.$order['cert_no'].')',
            'goods_name' => $order['goods_title'],
            'setmeal_name' => $order['setmeal_title'],
            'amount' => $order['amount'],
            // 'setmeal_foregift' => $order['setmeal_foregift'],
            'is_new' => $order['new_grade']<100?'否':'是',
            'meal' => $order['pact_type'],
            'goods_price' => $order['website_price'].'元',
            // 'total_rent' => sprintf("%.2f",$order['website_price']*$order['amount']).'元',
            'total_rent1' => $order['rent_total'].'元',
            // 'month_rent' => sprintf("%.2f",$order['rent_total']/$order['month_total']).'元',
            'first_month_rent'=>$fisrt_month_rent,
            'month_rent' => $month_rent.'元'.'（月租金=(总租金-首付金)/期数）',
            'lease_term' =>  date('Y.m.d',strtotime($order['begin_time'])).'-'.date('Y.m.d',strtotime($order['end_time'])),
            'pay_type' => '分期付租',
            'amount_pay' => $order['isBuyout']==1?$order['setmeal_foregift'].'元':$order['is_buy_out'],
            'buy_out_price' => '0.00元',
            'receiving_address' => $order['address'],
            'user_name1' => $order['cert_name'],
            'user_mobile1' => $order['user_mobile'],
            'user_address1' => $order['address'],
            'email'=>$order['user_email'],
            'first_name1' => $shop_user['mechanism'],
            'first_mobile1' => $shop_user['contact_tel'],
            'first_address1' => $shop_user['company'],
            'first_name2' => $shop_user['mechanism'],
            'user_name2' => $order['cert_name'],
            'third_name2' => '',
            'sign_year' => date("Y"),
            'sign_month' => date("m"),
            'sign_day' => date("d"),
            'insurance_price' => GoodsService::getGoodsInsurance($order['is_insurance_choose'],$order['is_insurance_choose_custom']).'元（与第一期租金一并支付）',
        );
        fopen('/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf', 'w');
        $data = [
//            'streamFile'=>file_get_contents('租赁合同支付宝端20241110.pdf'),
            'templateFillParam'=>json_encode([
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/租赁合同微信1120.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf',
                ],
                'txtFields'=>$txtFields
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/doc/createFileFromTemplate',$data);

        self::addLog('填充本地PDF模板文件',$data,$return_content);
        $result = (array)json_decode($return_content,true);

        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }
        //平台方
        $data = [
//            'streamFile'=>$result['stream'],
            'platformSignParam'=>json_encode([
                'sealSpec'=>'IMAGE',
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf',
                ],
                'sealId'=>'97ea1d59-98de-400c-bd42-e4af6a6a9ce1',
                'signType' => 'Single',
                'sealSpec' => 'IMAGE',
                'posBeans' =>[
                    [
                        'posPage' => 16,
                        'posX' => 190,
                        'posY' => 430
                    ]
                ],
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/platform/sign',$data);
        self::addLog('填充本地PDF模板文件',$data,$return_content);

        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }
        //商户方
        $data = [
            'orgSignParam'=>json_encode([
                'accountId'=>$shop_user['esign_shop_id'],
                'sealData'=>$shop_user['esign_seal_id'],
                'sealSpec'=>'IMAGE',
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf',
                ],
                'signType' => 'Single',
                'posBeans' =>[
                    [
                        'posPage' => 16,
                        'posX' => 190,
                        'posY' => 679
                    ]
                ],
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/user/sign/orgSign',$data);
        self::addLog('商户方填充本地PDF模板文件',$data,$return_content);

        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }


        //个人
        $flowId=MemberOther::query()->where('id',$order['uid'])->value('certify_id');
        $data = [
            'personSignParam'=>json_encode([
                'accountId'=>$member['esign_user_id'],
                'sealData'=>$member['esign_seal_id'],
                'willingnessId'=>$flowId,
                'sealSpec'=>'IMAGE',
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf',
                ],
                'signType' => 'Single',
                'posBeans' =>[
                    [
                        'posPage' => 16,
                        'posX' => 190,
                        'posY' => 560
                    ]
                ],
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/user/sign/personSign',$data);
        self::addLog('个人填充本地PDF模板文件',$data,$return_content);

        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }

        $fileName = $order['trade_no'].".pdf";
        $path = '/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'.pdf';
        $uploud_res = AlipayService::upload($fileName,$path);
        if($uploud_res['status']){
                if(file_exists($path)){
                    unlink($path);
                }
            return ['status'=>CommonService::HTTP_CODE_SUCCESS,'message'=>'合同生成成功','url'=>config('alipay.oss.imgHost').$order['trade_no'].'.pdf'];
        }else{
            throw new BaseException($uploud_res['message']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$uploud_res['message']];
        }



    }

    //创建个人模板印章
    public static function personaltemplate($accountId){
        $arr = array(
            'type'=>'RECTANGLE',
            'color'=>'RED',
            'accountId'=>$accountId);
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.API_HOST_V3').'/timevale/seal/createPersonSeal',$data);
        $result = (array)json_decode($return_content,true);
        self::addLog('创建个人模板印章',$data,$return_content);

        return $result['sealData'];
    }

    //通过模板创建文件
    public static function createByTemplate($arr){
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.createByTemplate'),$data,config('esign.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        if(isset($result['data']) && !empty($result['data']['fileId'])){
            return $result['data']['fileId'];
        }else{
            return $result;
        }
    }

    //设置静默签署
    public static function SetSignAuth($esign_account_id){
        $addaDocumnet = str_replace('{accountId}',$esign_account_id,config('esign.SetSignAuth'));
        $return_content = self::doPost($addaDocumnet,'',config('esign.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        if($result && !empty($result['data']['docs'])){
            $result_data = $result['data']['docs'];
            return $result_data[0];
        }
    }

    //签署流程撤销
    public static function revoke($flowId){
        $addaDocumnet = str_replace('{flowId}',$flowId,config('esign.revoke'));
        $arr = array(
            'operatorId' => config('esign.ACCOUNT')
        );
        $data = json_encode($arr);
        $return_content = self::sendHttpPUTCommon($addaDocumnet,$data,config('esign.APPID'),self::getToken());
        return $return_content;
    }

    public static function downloadDocument($flowid){
        $downloadDocument = str_replace('{flowId}',$flowid,config('esign.downloadDocument'));
        $return_content = self::get_data($downloadDocument,config('esign.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        if($result && !empty($result['data']['docs'])){
            $result_data = $result['data']['docs'];
            return $result_data[0];
        }
    }


    public static function get_data($url) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        return $return_content;
    }

    public static function doGet($url, $data)
    {
        list($return_code, $return_content) = self::curl_get_https($url, $data);
        return $return_content;
    }



    public static function http_post_wx_data($url, $data, $appID, $stoken) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Tsign-Open-App-Id:".$appID,"X-Tsign-Dns-App-Id:".$appID, "X-Tsign-Open-Token:".$stoken, "Content-Type:application/json" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
//        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $return_content;
    }


    public static function doPost($url, $data)
    {
        list($return_code, $return_content) = self::http_post_data($url, $data);

        return $return_content;
    }


    /**
     * 常规请求
     * @param $reqType
     * @param $url
     * @param $paramStr
     * @return EsignResponse
     */
    public  static function doCommHttp($reqType, $url, $paramStr){
//		get和delete方式请求不能携带body体
        if(strtoupper($reqType)=="GET"||strtoupper($reqType)=="DELETE"){
            $paramStr=null;
        }
        //对body体做md5摘要
        $contentMd5=self::getContentMd5($paramStr);

        //传入生成的bodyMd5,加上其他请求头部信息拼接成字符串,整体做sha256签名
        $reqSignature = self::getSignature($reqType,"*/*","application/json; charset=UTF-8",$contentMd5,"","",$url);
        var_dump($reqSignature);
        return self::sendHttp($reqType, $url, self::buildCommHeader($contentMd5,$reqSignature),$paramStr);
    }

    //常规请求类
    public static function sendHttp($reqType='GET', $url, $headers=array(), $param=null)
    {
        $logData = [
            'url' => $url,
            'httpMethod' => $reqType,
            'data' => $param,
            'header' => $headers
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $reqType);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $postData = is_array($param) ? json_encode($param, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : $param;
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        if (self::$readTimeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, self::$readTimeout);
        }
        if (self::$connectTimeout) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout);
        }
        //https request
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (is_array($headers) && 0 < count($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        $curlRes = curl_exec($ch);



        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlRes=json_decode($curlRes,true);
//        var_dump($curlRes);
        curl_close($ch);
        return compact('curlRes','httpCode');
    }

    /**
     * 获取MD5
     * @param $bodyData
     * @return string
     */
    public static function getContentMd5($bodyData)
    {
        return base64_encode(md5($bodyData, true));
    }

    /**
     * 生成签名
     * @param $httpMethod
     * @param $accept
     * @param $contentType
     * @param $contentMd5
     * @param $date
     * @param $headers
     * @param $url
     * @return string
     */
    public static function getSignature($httpMethod, $accept, $contentType, $contentMd5, $date, $headers, $url)
    {

        $stringToSign = $httpMethod . "\n" . $accept . "\n" . $contentMd5 . "\n" . $contentType . "\n" . $date . "\n" . $headers;
        if ($headers != '') {
            $stringToSign .= "\n" . $url;
        } else {
            $stringToSign .= $url;
        }
        $signature = hash_hmac("sha256", utf8_encode($stringToSign), utf8_encode(config('esign.SECRET')), true);
        $signature = base64_encode($signature);
        return $signature;
    }

    /**
     * 构造头部信息
     * @param $contentMD5
     * @param $reqSignature
     * @return array
     */
    public static function buildCommHeader($contentMD5,$reqSignature){
        $headers = array(
            'X-Tsign-Open-App-Id:'.config('esign.APPID'),
            'X-Tsign-Open-Ca-Timestamp:'.self::getMillisecond(),
            'Accept:*/*',
            'X-Tsign-Open-Ca-Signature:'.$reqSignature,
            'Content-MD5:'.$contentMD5,
            'Content-Type:application/json; charset=UTF-8',
            'X-Tsign-Open-Auth-Mode:Signature'
        );
        return $headers;
    }

    /**
     * 生成13位时间戳
     * @return float
     */
    public static function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }


    public static function http_post_data($url, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    public static function doGeta($url, $data,$appID, $stoken)
    {
        list($return_code, $return_content) = self::http_sign_get_data($url, $data, $appID, $stoken);
        return $return_content;
    }

    public static function http_sign_get_data($url, $data, $appID, $stoken) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Tsign-Open-App-Id:".$appID, "X-Tsign-Open-Token:".$stoken, "Content-Type:application/json;charset=UTF-8" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }


    public static function curl_get_https($url, $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    public static function sendHttpPUT($uploadUrls, $contentMd5, $fileContent){
        $header = array(
            'Content-Type:application/pdf',
            'Content-MD5:' . $contentMd5
        );

        $status = '';
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $uploadUrls);
        curl_setopt($curl_handle, CURLOPT_FILETIME, true);
        curl_setopt($curl_handle, CURLOPT_FRESH_CONNECT, false);
        curl_setopt($curl_handle, CURLOPT_HEADER, true); // 输出HTTP头 true
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_handle, CURLOPT_TIMEOUT, 5184000);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 120);
        curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'PUT');

        curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $fileContent);
        $result = curl_exec($curl_handle);
        $status = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);

        if ($result === false) {
            $status = curl_errno($curl_handle);
            $result = 'put file to oss - curl error :' . curl_error($curl_handle);
        }
        curl_close($curl_handle);
        return $status;
    }

    public static function sendHttpPUTCommon($url, $data, $appID, $stoken) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');

        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Tsign-Open-App-Id:".$appID, "X-Tsign-Open-Token:".$stoken, "Content-Type:application/json" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        return $return_content;
    }


    /**
     * E签宝合同
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function addLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::channel("esign")->debug($message, $content);
    }


    //【人脸识别认证】个人实名-唤起
    public static function checkFaceAuth($contextId,$name,$cert_no,$type=1){
        //认证结束后异步通知地址
        if($type == '1'){ //下单
            $arr['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_AUTH_FACE_URL;
        }else if($type == '2'){ //签署合同
            $arr['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_AUTH_FACE_URL_SIGN;
        }
        $data = [
            'name'=>$name,
            'idNo'=>$cert_no,
            'contextId'=>$contextId,
            'callbackUrl'=>'wechat://back',
            'certType'=>'INDIVIDUAL_CH_IDCARD',
            'faceauthMode'=>'ZHIMACREDIT',
            'authType'=>'PSN_FACEAUTH_BYURL',
            'availableAuthTypes'=>["PSN_FACEAUTH_BYURL"]
        ];
        $data=array_merge($data,$arr);
        $return_content = IdCardService::indivAuthUrl($data);
        $result = $return_content['curlRes'];

        self::addLog('个人实名认证',$data,$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['flowId'])){
            return $result['data'];
        }else{
           throw new ApiException($result['message']);
        }
    }



    //【人脸识别认证】个人实名-web唤起
    public static function checkWechatWebFaceAuth($contextId,$name,$cert_no,$type=1,$isAlipay=1){
        //认证结束后异步通知地址
        if($type == '1'){ //下单
            $arr['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_AUTH_WXFACE_URL;
        }else if($type == '2'){ //签署合同
            $arr['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_AUTH_FACE_URL_SIGN;
        }

        $data = [
            'name'=>$name,
            'idNo'=>$cert_no,
            'contextId'=>$contextId,
            'callbackUrl'=>'wechat://back',
            'certType'=>'INDIVIDUAL_CH_IDCARD',
            'faceauthMode'=>$isAlipay==1?'ZHIMACREDIT':'WE_CHAT_FACE',
            'authType'=>'PSN_FACEAUTH_BYURL',
            'availableAuthTypes'=>["PSN_FACEAUTH_BYURL"]
        ];
        $data=array_merge($data,$arr);
        $return_content = IdCardService::indivAuthUrl($data);
        $result = $return_content['curlRes'];

        self::addLog('个人实名认证',$data,$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['flowId'])){
            return $result['data'];
        }
    }

    //【人脸识别认证】个人实名-查询
    public static function selectFaceAuth($flowId){
        $faceAuthPhoto = str_replace('{flowId}',$flowId,config('esign.faceAuthPhoto'));
        $arr = array();
        $data = json_encode($arr);
        $return_content = self::doGeta($faceAuthPhoto,$data,config('esign.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        self::addLog('人脸识别认证返照',$data,$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['flowId'])){
            return $result['data'];
        }
    }

    /**
     * 查看人脸图片
     * @param $flowId
     * @return mixed|void
     */
    public static function findFace($flowId,$accountId){
        $arr = array(
            'accountId'=>$accountId,//认证完成后重定向地址
            'flowId'=>$flowId //自定义业务标识
        );
        $data = json_encode($arr);
        $return_content = self::doPost(config('esign.faceImage'),$data,config('esign.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);
        var_dump($data);
        var_dump($return_content);
        self::addLog('查询签署中认证信息',$data,$return_content);
        if($result['code'] == 0 && isset($result['data']) && !empty($result['data']['identityFlowId'])){
            return $result['data'];
        }
    }

    /**
     * 征信-个人信用报告授权书
     * userAuthProtocol
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createIncestUserAuthCall($order){

        $simpleFormFields=array(
            "name" => $order['cert_name'], //姓名
            "year" => date("Y"),
            "month" => date("m"),
            "day" => date("d")
        );
        fopen('/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'protocol.pdf', 'w');
        $data = [
            'templateFillParam'=>json_encode([
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/用户授权协议征信.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'protocol.pdf',
                ],
                'txtFields'=>$simpleFormFields
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/doc/createFileFromTemplate',$data);

        self::addLog('填充本地PDF模板文件',$data,$return_content);
        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }
        //个人
        $flowId=MemberOther::query()->where('id',$order['uid'])->value('certify_id');
        $data = [
            'personSignParam'=>json_encode([
                'accountId'=>$order['esign_user_id'],
                'sealData'=>$order['esign_seal_id'],
                'willingnessId'=>$flowId,
                'sealSpec'=>'IMAGE',
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'protocol.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'protocol.pdf',
                ],
                'signType' => 'Single',
                'posBeans' =>[
                    [
                        'posPage' => 1,
                        'posX' => 470,
                        'posY' => 145
                    ]
                ],
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/user/sign/personSign',$data);

        self::addLog('用户授权协议征信-userAuthProtocol',$data,$return_content);
        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }

        return ['status'=>CommonService::HTTP_CODE_SUCCESS,'message'=>'合同生成成功','data'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'protocol.pdf'];

    }

    /**
     * 征信-用户授权协议
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createCreditAuth($order){

        //发起签署
        $templateId = config('esign.TEMPLATE_ID_2');//用户授权协议模板ID
        $order_arr = array(
            'name'=>'用户授权协议.pdf',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                'name' => $order['cert_name'],
                'cert' => $order['cert_no'],
                'mobile' => $order['user_mobile'],
                "year" => date("Y"),
                "month" => date("m"),
                "day" => date("d")
            )
        );

        $fileId = self::createByTemplate($order_arr);

        if(!empty($order['esign_user_id'])){
            self::SetSignAuth($order['esign_user_id']);//设置静默签署
            self::SetSignAuth(config('esign.ACCOUNT'));//设置静默签署
        }else{
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'个人签署账号不存在'];
        }

        //签章
        $step_data['docs'][0]['fileId'] = $fileId;
        $step_data['docs'][0]['fileName'] = '用户授权协议.pdf';
        $step_data['docs'][0]['sealId'] = $order['esign_seal_id'];
        $step_data['flowInfo']['autoArchive'] = true;
        $step_data['flowInfo']['autoInitiate'] = true;
        $step_data['flowInfo']['businessScene'] = '用户授权协议';
        $step_data['flowInfo']['flowConfigInfo']['noticeDeveloperUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_SLIENCE;
        $step_data['flowInfo']['initiatorAccountId'] =  config('esign.ACCOUNT');
        $step_data['flowInfo']['initiatorAuthorizedAccountId'] = config('esign.ACCOUNT');


        $step_data['signers'][0]['signerAccount']['signerAccountId'] =  $order['esign_user_id'];
        $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        $step_data['signers'][0]['signfields'][0]['sealType'] = 0;

        $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 1;
        $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 390;
        $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 115;

        $data = json_encode($step_data);
        $return_content = self::doPost(config('esign.createFlowOneStep'),$data,config('esign.APPID'),self::getToken());
        $result = (array)json_decode($return_content,true);

        self::addLog('一步发起签署-用户授权协议',$data,$return_content);

        return $result;

    }

    /**
     * 征信-融资租赁委托担保合同
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createCreditCompanyAuth($order,$orgid,$seal_id){

        //发起签署
        $templateId = config('esign.TEMPLATE_ID_3');//融资租赁委托担保合同模板ID
        $order_arr = array(
            'name'=>'融资租赁委托担保合同.pdf',
            'templateId'=>$templateId,
            'simpleFormFields'=>array(
                "platformLoanNo"=>$order['trade_no'],
                'name' => $order['cert_name'],
                'idcardNumber' => $order['cert_no'],
                'mobile' => $order['user_mobile'],
                'website' => '挺想租',
                'loanStartDate' => date('Y年m月d日'),
                'partner' => $order['mechanism'],
                'payMoney' => sprintf("%.2f",$order['rent_total']/$order['month_total']).'元', //每月租金
                'periodNum' => $order['month_total'],  //总租期
                'buyoutPriceMoney' => sprintf("%.2f",$order['setmeal_foregift']-$order['rent_total']),  //买断款
                'loanMoney' => $order['rent_total'],  //总租金
                "guaranteeRate"=>"0.01%",//担保费率
                "guaranteeFee"=>sprintf("%.2f",$order['rent_total']*0.0001), //担保费用
                'currentDateYmd' => date('Y年m月d日')
            )
        );

        $fileId = self::createByTemplate($order_arr);

        if(!empty($orgid)){
            self::SetSignAuth($order['esign_user_id']);//设置静默签署
            self::SetSignAuth($orgid);//设置静默签署
        }else{
            throw new BaseException('签署账号不存在');
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>'签署账号不存在'];
        }

        //签章
        $step_data['docs'][0]['fileId'] = $fileId;
        $step_data['docs'][0]['fileName'] = '融资租赁委托担保合同.pdf';
        $step_data['docs'][0]['sealId'] = $order['esign_seal_id'];
        $step_data['flowInfo']['autoArchive'] = true;
        $step_data['flowInfo']['autoInitiate'] = true;
        $step_data['flowInfo']['businessScene'] = '融资租赁委托担保合同';
        $step_data['flowInfo']['flowConfigInfo']['noticeDeveloperUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_COMPANY;
        $step_data['flowInfo']['initiatorAccountId'] =  config('esign.ACCOUNT');
        $step_data['flowInfo']['initiatorAuthorizedAccountId'] = config('esign.ACCOUNT');


        // $step_data['signers'][0]['signerAccount']['authorizedAccountId'] = $orgid;
        // $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        // $step_data['signers'][0]['signfields'][0]['actorIndentityType'] = 2;
        // $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        // $step_data['signers'][0]['signfields'][0]['sealType'] = 2;

        // $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 5;
        // $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 185;
        // $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 173;

        $step_data['signers'][0]['signerAccount']['signerAccountId'] =  $order['esign_user_id'];
        $step_data['signers'][0]['signfields'][0]['autoExecute'] = true;
        $step_data['signers'][0]['signfields'][0]['fileId'] = $fileId;
        $step_data['signers'][0]['signfields'][0]['sealType'] = 0;

        $step_data['signers'][0]['signfields'][0]['posBean']['posPage'] = 5;
        $step_data['signers'][0]['signfields'][0]['posBean']['posX'] = 400;
        $step_data['signers'][0]['signfields'][0]['posBean']['posY'] = 100;
        // dd($step_data);
        $data = json_encode($step_data);
        $return_content = self::doPost(config('esign.createFlowOneStep'),$data,config('esign.APPID'),self::getToken());

        $result = (array)json_decode($return_content,true);
        // dd($result);
        self::addLog('一步发起签署-融资租赁委托担保合同',$data,$return_content);

        return $result;

    }


    /**
     * 布尔-个人信信息报告授权书
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createBoolUserAuth($order){

        $simpleFormFields=array(
            "name" => $order['cert_name'], //姓名
            "year" => date("Y"),
            "month" => date("m"),
            "day" => date("d")
        );
        fopen('/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'bool.pdf', 'w');
        $data = [
            'templateFillParam'=>json_encode([
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/bool授权.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'bool.pdf',
                ],
                'txtFields'=>$simpleFormFields
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/doc/createFileFromTemplate',$data);

        self::addLog('填充本地PDF模板文件',$data,$return_content);
        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }
        //个人
        $flowId=MemberOther::query()->where('id',$order['uid'])->value('certify_id');
        $data = [
            'personSignParam'=>json_encode([
                'accountId'=>$order['esign_user_id'],
                'sealData'=>$order['esign_seal_id'],
                'willingnessId'=>$flowId,
                'sealSpec'=>'IMAGE',
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'bool.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'bool.pdf',
                ],
                'signType' => 'Single',
                'posBeans' =>[
                    [
                        'posPage' => 1,
                        'posX' => 470,
                        'posY' => 145
                    ]
                ],
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/user/sign/personSign',$data);

        self::addLog('一步发起签署-个人信息报告授权书',$data,$return_content);
        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }

       return ['status'=>CommonService::HTTP_CODE_SUCCESS,'message'=>'合同生成成功','data'=>$result];


    }

    /**
     * 2024征信-个人信用报告授权书
     * pbcCreditAuth
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function createIncestUserAuth($order){

        $simpleFormFields=array(
            "name" => $order['cert_name'], //姓名
            "year" => date("Y"),
            "month" => date("m"),
            "day" => date("d")
        );
        fopen('/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'credit.pdf', 'w');
        $data = [
            'templateFillParam'=>json_encode([
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/个人征信授权书新.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'credit.pdf',
                ],
                'txtFields'=>$simpleFormFields
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/doc/createFileFromTemplate',$data);

        self::addLog('填充本地PDF模板文件',$data,$return_content);
        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }
        //个人
        $flowId=MemberOther::query()->where('id',$order['uid'])->value('certify_id');
        $data = [
            'personSignParam'=>json_encode([
                'accountId'=>$order['esign_user_id'],
                'sealData'=>$order['esign_seal_id'],
                'willingnessId'=>$flowId,
                'sealSpec'=>'IMAGE',
                'fileBean'=>[
                    'fileName'=>'租赁合同',
                    'srcPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'credit.pdf',
                    'dstPdfFile'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'credit.pdf',
                ],
                'signType' => 'Single',
                'posBeans' =>[
                    [
                        'posPage' => 1,
                        'posX' => 470,
                        'posY' => 145
                    ]
                ],
            ])
        ];
        $return_content = self::doMultipart(config('esign.API_HOST_V3').'/timevale/user/sign/personSign',$data);

        self::addLog('个人征信授权书新-credit',$data,$return_content);
        $result = (array)json_decode($return_content,true);
        if($result['errCode']){
            throw new BaseException($result['msg']);
            return ['status'=>CommonService::HTTP_CODE_FAIL,'message'=>$result['msg']];
        }

        return ['status'=>CommonService::HTTP_CODE_SUCCESS,'message'=>'合同生成成功','data'=>'/www/wwwroot/apishop.doulaizuji.com/public/pdf/'.$order['trade_no'].'credit.pdf'];
    }



    public static function doMultipart($url, $data) {
        list($return_code, $return_content) = self::http_multipart_data($url, $data);
        return $return_content;
    }

    public static function http_multipart_data($url, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 跳过检查
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data" ));
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return array($return_code, $return_content);
    }



}
